<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2021/3/18
 * Time: 16:28
 */

namespace App\Services\Project;

use App\Models\Project;
use App\ProjectInspect;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid\Tools\BatchActions;
use Encore\Admin\Grid\Tools\Selector;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;

class ProjectService
{
    public function gridColumn(\Encore\Admin\Grid $grid, $type = 1)
    {
        $grid->quickSearch('name', 'code')->placeholder('项目名称/项目编号');
        $grid->disableFilter();
        if ($type == 2) {
            return $this->gridColumnH($grid);
        }
        $review = request()->review;
        $grid->model()->when($review == 1, function ($query) {
            $query->where('review_status', 1)->whereIn('state', [0, 2]);
        })->when($review == 2, function ($query) use ($grid) {
            $query->where('review_status', 1)->where('state', 1);
        })->when($review == 3, function ($query) use ($grid) {
            $query->where('review_status', 1);
        })->when($review == 4, function ($query) use ($grid) {
            $query->whereIn('review_status', [0,2]);
        });
        if ($review && $review!=4) {
            $grid->disableCreateButton();
        }
        $grid->model()->with(['plans'])->where('type', $type);
        $grid->column('code', __('项目编号'));
        $grid->column('name', __('项目名称'))->modal('详情', function ($model) {
            return self::detail($model);
        });
        $grid->column('project_category', __('project.category'));
        $grid->column('amount', __('project.fee_authorize'));
        $grid->column('start_date', __('project.start_date'));
        $grid->column('state', '项目状态')->display(function ($state) {
            if ($this->review_status == 1) {
                return collect(['进行中','已完成','已暂停','已撤销'])->get($state);
            } else {
                return '';
            }
        });
        $grid->column('user.name', __('负责人'));
        $grid->column('review_status', __('审核状态'))
            ->using(['待审批', '通过', '未通过'])
            ->label(['warning', 'success', 'default']);

        $grid->batchActions(function (BatchActions $actions) {
            $actions->disableDeleteAndHodeSelectAll();
        });
        $grid->export(function (\Encore\Admin\Grid\Exporters\CsvExporter $export) {
            $export->filename('纵向项目');
            $export->originalValue(['name']);
            $export->column('review_state', function ($value, $original) {
                $arr = ['待审核', '审核通过', '审核未通过'];
                return $arr[$original] ?? '';
            });
        });
        return $grid;
    }

    public static function detail(Project $project)
    {
        if ($project->type == 2) {
            return self::detailH($project);
        }
        $tab = new Tab();
        $tab->add('基本信息', Admin::show($project, function (Show $show) use ($project) {
            $show->panel()->view('show.tab-panel');
            $show->field('code', __('project.code'));
            $show->field('name', __('project.name'));
            $show->field('department.name', __('Department'));

            $show->field('project_category', __('project.category'));
            $show->field('subject_category', __('project.subject_type'));
            if ($project->type == 1) {
                $show->field('project_level_id', __('project.level'))->using(project_level_options());
                $show->field('subject', __('project.subject'));
                $show->field('project_source', __('project.source'));
            }
            $show->field('approval_date', __('project.authorize_date'));
            $show->field('start_date', __('project.start_date'));
            $show->field('plan_end_date', __('project.plan_end_date'));
            $show->field('end_date', __('project.end_date'));
        }));
        $tab->add('负责人', Admin::show($project, function (Show $show) {
            $show->panel()->view('show.tab-panel');
            $show->field('user.username', __('用户名'));
            $show->field('user.name', __('姓名'));
            $show->field('user.eno', __('职工号'));
            $show->field('user.mobile', __('电话'));
            $show->field('user.email', __('邮箱'));
        }));
        $tab->add('其它成员', Admin::show($project, function (Show $show) {
            $show->panel()->view('show.tab-panel');
            $show->field('members', __(' '))->setWidth(12)->unescape()->as(function ($members) {
                $arr = collect($members)->map(function ($item) {
                    return [
                        'type' => $item['type'] ?? '',
                        'name' => $item['name'] ?? '',
                        'eno' => $item['eno'] ?? '',
                        'zch' => $item['zch'] ?? '',
                        'identity' => $item['identity'] ?? '',
                    ];
                })->values()->all();
                $table = new Table(['类型', '姓名', '工号', '职称', '承担类型'], $arr);
                return $table;
            });
        }));
        $tab->add('经费信息', Admin::show($project, function (Show $show) use ($project) {
            $show->panel()->view('show.tab-panel');
            $show->field('amount', __('project.fee_authorize'));
            $show->field('inside_amount', __('project.attach_fee'));
            if ($project->type == 1) {
                $show->field('out_fee', __('project.out_fee'));
            }
        }));
        return $tab;
    }

    public function gridColumnH(\Encore\Admin\Grid $grid)
    {
        $grid->batchActions(function (BatchActions $actions) {
            $actions->disableDeleteAndHodeSelectAll();
        });
        $grid->model()->with(['bills'])->where('type', 2);
        $grid->column('code', __('项目编号'));
        $grid->column('name', __('项目名称'))->modal('详情', function ($project) {
            return self::detail($project);
        });
        $grid->column('contract_type', __('合同类型'));
        $grid->column('domain', __('所属领域'))->hide();
        $grid->column('entrust_company', __('委托单位'))->hide();
        $grid->column('sign_date', __('签订时间'));
        $grid->column('amount', __('合同金额'));
        $grid->column('out_amount', __('预计外拨金额'));
        $grid->column('_bills', __('到账金额'))->display(function () {
            return $this->bills->sum('amount');
        });
        $grid->column('user.name', __('负责人'));
        $grid->column('review_status', __('审批状态'))
            ->using(['待审批', '审批通过', '审批未通过'])
            ->label(['warning', 'success', 'default']);
        $grid->export(function (\Encore\Admin\Grid\Exporters\CsvExporter $export) {
            $export->filename('项目审批');
            $export->except(['detail']);
            $export->originalValue(['name']);
            $export->column('review_status', function ($value, $original) {
                $arr = ['待审批', '审批通过', '审批未通过'];
                return $arr[$original] ?? '';
            });
        });
        return $grid;
    }

    public static function detailH(Project $project)
    {
        $tab = new Tab();
        $tab->add('基本信息', Admin::show($project, function (Show $show) {
            $show->panel()->view('show.tab-panel');
            $show->fields([
                'code' => '项目编号',
                'name' => '项目名称',
                'contract_type' => '合同类型',
                'domain' => '所属领域',
                'entrust_company' => '委托单位',
                'amount' => '合同金额',
                'sign_date' => '签订时间',
                'sign_address' => '签订地点',
                'assist_company' => '外协单位',
                'out_amount' => '预计外拨金额'
            ]);
        }));
        $tab->add('项目负责人', Admin::show($project, function (Show $show) {
            $show->panel()->view('show.tab-panel');
            $show->field('user.username', '账号');
            $show->field('user.name', '姓名');
            $show->field('user.mobile', '联系电话');
            $show->field('user.email', '邮箱');
        }));
        $tab->add('到账信息', Admin::show($project, function (Show $show) {

            $show->panel()->view('show.tab-panel');
            $show->field('_bills', __(' '))->setWidth(12)->unescape()->as(function ($bill) {
                $arr = $this->bills->map(function ($item) {
                    return [
                        $item['amount'] ?? '',
                        $item['date'] ?? ''
                    ];
                })->values()->all();
                $table = new Table(['到账金额', '到账时间'], $arr);
                return $table;
            });
        }));
        $style = <<<STYLE
.nav-tabs-custom>.nav-tabs {
        border-bottom-color: #3c8dbc;
    }
    .nav-tabs-custom>.nav-tabs>li.active>a {
        border-left-color: #3d6e8a;
        border-right-color: #3d6e8a;
    }
STYLE;
        Admin::style($style);
        return $tab;
    }

    public function inspectGridColumn(\Encore\Admin\Grid $grid, $type = [1, 3])
    {
        $that = $this;
        $grid->model()->with('project')->whereIn('state', [0, 2])
            ->whereHas('project', function (Builder $query) use ($type) {
                $query->where('state', 0)
                    ->where('review_status', 1);
            });
        $grid->column('project.code', __('项目编号'));
        $grid->column('project.name', __('项目名称'))
            ->modal('详情', function ($obj) use ($that) {
                if ($obj->project->type == 3) {
                    return $that->detailH($obj->project);
                }
                return $that->detail($obj->project);
            });
        $grid->column('project.type', __('项目类型'))
            ->using(['', '横向项目', '纵向项目', '校级项目'])->label(['default', 'info', 'success', 'primary']);
        $grid->column('inspect.name', __('中检名称'));
        $grid->column('file', __('附件'))->downloadable();
        $grid->column('state', __('中检状态'))
            ->using(['未中检', '中检已通过', '中检未通过']);
        $grid->disableCreateButton();
        $grid->disableFilter();
        $grid->batchActions(function (BatchActions $actions) {
            $actions->disableDeleteAndHodeSelectAll();
        });
        $grid->selector(function (Selector $selector) {
            $selector->selectOne('type', '项目类型', [1 => '纵向项目', 3 => '校级项目'], function ($query, $value) {
                $query->whereHas('project', function (Builder $query) use ($value) {
                    $query->where('type', $value);
                });
            });
            $selector->select('project_inspect_id', '中检计划', ProjectInspect::pluck('name', 'id'));
        });
        $grid->quickSearch(function ($model, $input) {
            $model->whereHas('project', function (Builder $query) use ($input) {
                $query->where('code', 'like', "%{$input}%")
                    ->orWhere('name', 'like', "%{$input}%");
            });
        })->placeholder('项目名称/项目编号');
        return $grid;
    }
}
